package cc.angis.xiugallery;

import java.util.ArrayList;
import java.util.List;

import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.widget.Toast;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.db.FavouriteImagesDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.image.ui.JBImageGridFragment;

import com.actionbarsherlock.app.ActionBar;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

@SuppressLint("NewApi") 
public class MainActivity extends SlidingFragmentActivity {
	
	private final String CALLBACKURL = "yydzxe://mainactivity";  
	
	protected static final Intent SERVICE_INTENT = new Intent();
	static {
//		SERVICE_INTENT.setComponent(new ComponentName(
//				"im.keep",
//				"im.keep.service.MaxMessageService"));
		SERVICE_INTENT.setComponent(new ComponentName(
				"cc.angis.xiugallery",
				"cc.angis.xiugallery.service.CommentService"));
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// set the Above View
		setContentView(R.layout.pager);
		startService(SERVICE_INTENT);
		this.getSharedPreferences(GlobalConst.PREF_NAME, 0).edit().putInt(GlobalConst.PREF_CUR_INDEX, 0).commit();
		if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content, JBImageGridFragment.newInstance(GlobalConst.CAMERA_IMAGE_BUCKET_ID, GlobalConst.INTENT_GROUP_TYPE_GALLERY, GlobalConst.MenuType.MENU_TYPE_IMAGEDISPLAY, ""), GlobalConst.TAG_FRAGMENT_FAVOURITE);
            ft.commit();
        }		
		
		ActionBar actionbar = this.getSupportActionBar();
		actionbar.setDisplayHomeAsUpEnabled(true);
		// set the Behind View
		setBehindContentView(R.layout.frame);
		android.support.v4.app.FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
		t.replace(R.id.frame, new SampleListFragment());
		t.commit();

		// customize the SlidingMenu
		this.setSlidingActionBarEnabled(true);
		getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
		getSlidingMenu().setShadowDrawable(R.drawable.shadow);
		getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);
		getSlidingMenu().setBehindScrollScale(0.5f);
		
		sendBroadcast(new Intent(Intent.ACTION_MEDIA_REMOVED, Uri.parse("file://"  
                + Environment.getExternalStorageDirectory())));
		
		new ScanTask().execute();

	}
	
	@Override  
    protected void onNewIntent(Intent intent) {  
        super.onNewIntent(intent);  
        Uri uri = intent.getData();  
        if (uri != null && uri.toString().startsWith(CALLBACKURL)) {  
            String verifier =  
                    uri.getQueryParameter("oauth_verifier");  
            try {  
                AccessToken oAuthAccessToken = new TwitterFactory().getInstance().getOAuthAccessToken(verifier);
                System.out.println("000");
            } catch (Exception e) {  
                e.printStackTrace();  
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();  
            }  
        }  
    }  
	
	public class PagerAdapter extends android.support.v4.app.FragmentPagerAdapter implements 
	ViewPager.OnPageChangeListener{

		private List<android.support.v4.app.Fragment> mFragments = new ArrayList<android.support.v4.app.Fragment>();
		private ViewPager mPager;

		public PagerAdapter(android.support.v4.app.FragmentManager fragmentManager, ViewPager vp) {
			super(fragmentManager);
			mPager = vp;
			mPager.setAdapter(this);
			mPager.setOnPageChangeListener(this);
		}
		
//		public void addTab(Fragment frag) {
//			mFragments.add(frag);
//			mActionBar.addTab(mActionBar.newTab().setTabListener(this).
//					setText("Tab "+mFragments.size()));
//		}
		
		@Override
		public android.support.v4.app.Fragment getItem(int position) {
			return mFragments.get(position);
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

//		@Override
//		public void onTabSelected(Tab tab, FragmentTransaction ft) {
//			mPager.setCurrentItem(tab.getPosition());
//		}
//
//		public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
//		public void onTabReselected(Tab tab, FragmentTransaction ft) { }
		public void onPageScrollStateChanged(int arg0) { }
		public void onPageScrolled(int arg0, float arg1, int arg2) { }

		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			
		}

	}
	
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch(item.getItemId()){
			case android.R.id.home:
				getSlidingMenu().showBehind();
				break;
			default:
				break;
		}
		return super.onOptionsItemSelected(item);
	}

//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		 SubMenu sub = menu.addSubMenu("Theme");
//	        sub.add(0, R.style.Theme_Sherlock, 0, "Default");
//	        sub.add(0, R.style.Theme_Sherlock_Light, 0, "Light");
//	        sub.add(0, R.style.Theme_Sherlock_Light_DarkActionBar, 0, "Light (Dark Action Bar)");
//	        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
//	        return true;
//	}
	
	public class ScanTask extends AsyncTask<String, Void, Integer>{

		@Override
		protected Integer doInBackground(String... params) {
			FavouriteImagesDBHelper dbHelper = new FavouriteImagesDBHelper(getApplicationContext(), TableConstants.TABLE_FAVOURITE_IMAGES);
			List<Long> imgs;
			try{
				imgs = dbHelper.getAllFav();
				StringBuilder builder = new StringBuilder();
				if (imgs.size() > 0){
					for (Long id:imgs){
						builder.append("'").append(id).append("'").append(",");
					}
					Cursor cursor = MainActivity.this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
							new String[]{MediaStore.Images.Media._ID}, "_id IN (" + builder.substring(0, builder.length()-1) + ")", null, null);
					if(cursor.moveToFirst()){
						do{
							imgs.remove(cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
						} while(cursor.moveToNext());
					}
					cursor.close();
					builder = new StringBuilder();
					if(imgs.size()>0){
						for (Long id:imgs){
							builder.append("'").append(id).append("'").append(",");
						}
						
						dbHelper.deleteIn(builder.substring(0, builder.length()-1));
					}
				}
			} catch(Exception e){
				e.printStackTrace();
			} finally{
				dbHelper.closeDB();
			}
			return null;
		}
		
	}

}
